package com.nulldev.util.encoding.nHash.hash2;

import com.nulldev.util.encoding.nHash.Hashable;
import com.nulldev.util.java.JVMUtil;
import com.nulldev.util.math.MathUtil;
import com.nulldev.util.other.RandomUtils.nRandom;

public class Hash2 implements Hashable<Integer> {
	public static int hash2(final byte[] data) {
		if (data == null || data.length == 0) {
			return -99;
		}
		final int len_len = String.valueOf(data.length).length();
		int hash = 0;
		hash = hash2_(data);
		return hash;
	}
	
	private static int hash2_(final byte[] data) {
		int val = 0; 
		for (int i = 0; i < data.length; i++) {
			if (val == 0) {
				// Set inital data
				val = data[i];
				continue;
			}else {
				// Calculate average
				val = (data[i] + val) / 2;
			}
		}
//		for (int i = 0; i < data.length; i++) {
//			val += data[i];
//		}
		if (val < 0) {
			return MathUtil.nonNegative(val);
		}
		return val;
	}

	public static void main(String[] args) {
		final nRandom nr = new nRandom();
		final byte[] randomData = nr.read(10240);
		JVMUtil.async_println("Hashing " + randomData.length + " bytes of data...");
		JVMUtil.async_println("Hash2 of data: " + hash2(randomData));
	}

	@Override
	public Integer hash(byte[] data) {
		return this.hash2(data);
	}

	@Override
	public String hasherID() {
		return "nhash.hash2";
	}

	@Override
	public String[] hashes() {
		return new String[] {"hash2", "Hash2"};
	}
}
